package com.spica.spicaschool.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.asLiveData
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.switchMap
import com.spica.spicaschool.base.LiveCoroutinesViewModel
import com.spica.spicaschool.bean.PageEntity
import com.spica.spicaschool.bean.diary.Diary
import com.spica.spicaschool.network.ResponseList
import com.spica.spicaschool.network.repository.CircleRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import javax.inject.Inject


/**
 * 圈子 ViewModel
 */
@HiltViewModel
class CircleViewModel @Inject constructor(
    private val circleRepository: CircleRepository
) : LiveCoroutinesViewModel() {


    private val pageEntityStateFlow: MutableStateFlow<PageEntity> = MutableStateFlow(PageEntity())

    private lateinit
    var _diariesLiveData: LiveData<ResponseList<Diary>>

    val diaryListLiveData: LiveData<ResponseList<Diary>>
        get() = _diariesLiveData.distinctUntilChanged()

    /**
     * 初始化
     */
    fun fetchDiaryList(
        token: String,
        type: Int,
        onStart: () -> Unit,
        onComplete: () -> Unit,
        onError: (String?) -> Unit
    ) {
        //每次页面切换时刷新数据
        _diariesLiveData = pageEntityStateFlow.asLiveData().switchMap { pageEntity ->
            circleRepository
                .fetchDiaryList(pageEntity, token, type, onStart, onComplete, onError)
                .asLiveDataOnViewModelScope()//绑定生命周期
        }
    }


    /**
     * 切换页码
     */
    fun pageChanged(pageEntity: PageEntity) {
        pageEntityStateFlow.value = pageEntity
    }


}